package deep.projects.newsapp.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import deep.projects.newsapp.adapters.NewsAdapter;
import deep.projects.newsapp.app.Urls;
import deep.projects.newsapp.beans.News;
import deep.projects.newsapp.beans.NewsType;

/**
 * NewsPageFragment 类为新闻 Fragment 显示页面
 * @author 吾心无待 于2016年03月05日
 */
public class NewsPageFragment extends BGARefreshLayoutFragment<NewsAdapter> {
    private NewsType mNewsType;

    /**
     * 获取新闻类型
     * @return 新闻类型
     */
    public NewsType getNewsType() {
        return mNewsType;
    }

    @Override
    public NewsAdapter getAdapter(Context context) {
        return new NewsAdapter(context);
    }

    @Override
    public void refresh(JSONObject jsonObject) {
        try {
            JSONArray arr = jsonObject.getJSONArray("items");
            mTotal = jsonObject.getInt("total");
            for (int i = 0; i < arr.length(); i++) {
                JSONObject obj = (JSONObject) arr.get(i);
                News p = News.itemFrom(obj);
                mAdapter.add(p);
            }
            mAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getPageItfFormat() {
        return Urls.PAGE_ITF_FORMAT_NEWS;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mAdapter != null){
            outState.putSerializable("data", mAdapter.getList());
            outState.putInt("page",mPage);
        }
    }

    @Override
    public void readInstanceState(@Nullable Bundle savedInstanceState) {
        ArrayList<News> data = (ArrayList<News>) savedInstanceState.getSerializable("data");
        mPage = savedInstanceState.getInt("page");
        mAdapter.addAll(data);
    }


    public static NewsPageFragment create(NewsType newsType){
        NewsPageFragment fragment = new NewsPageFragment();
        fragment.mNewsType = newsType;
        return fragment;
    }

    @Override
    public Object[] getPageItfParamValues() {
         return new Object[]{mNewsType.getId()};
    }
}
